package com.inapp.ocreader;

import java.io.File;
import java.io.FileOutputStream;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.DialogInterface.OnCancelListener;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.Toast;
import com.itwizard.mezzofanti.OCR;


public class ResultsActivity  extends Activity implements Runnable
{
	private static final String TAG = "ResultsActivity.java";
	private String m_sOCRResultLineMode = "";
	private boolean m_bLineMode = false;
    private boolean m_bMenuSettings = false;
    private int imgHeight, imgWidth;
    private EditText result_text;
    private String path = null;
    private ProgressDialog pdShowImage;

    // 'Menu' items
    Menu m_sPreferencesMenu = null;
	private static final int PREFERENCES_GROUP_ID = 0;
    private static final int SETTINGS_ID = Menu.FIRST;
    private static final int IN_IMAGE_ID = Menu.FIRST + 1;
    private static final int ABOUT_ID = Menu.FIRST + 2;    
    
	public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        
        try
        {
	        Log.v(TAG, "Starting Results Activity......");
	        
	        requestWindowFeature(Window.FEATURE_NO_TITLE);
	        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
	                WindowManager.LayoutParams.FLAG_FULLSCREEN);
	        
	        Window window = getWindow();
	        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
		        
	        GetDataFromMezzofanti();
	        setContentView(R.layout.result);
	        
	        result_text = (EditText) findViewById(R.id.result_text);
	    	DisplayOcrResult();
        }
        catch (Exception ex)
        {
        	Log.v(TAG, "exception: onCreate(): " + ex.toString());
        }
            
    }

    @Override
    protected void onResume() 
    {
      super.onResume();
      Log.v(TAG, "onResume() ----------------------------");
            
      if (m_bMenuSettings)
      {
    	  // currently in Settings-Menu, and we return to Capture 
    	  // so we store all the settings data in the local variables
    	  m_bMenuSettings = false;
		  SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);

    	  OCR.mConfig.GetSettings(prefs);
    	  OCR.ReadAvailableLanguages();
    	  CameraManager.SetImgDivisor(OCR.mConfig.GetImgDivisor());
      }
    }

    private void GetDataFromMezzofanti()
    {
        Bundle bun = getIntent().getExtras();
        if (null == bun) {
        	Log.v(TAG,"Bundle is null");
        }
        else {
        	 m_bLineMode = bun.getBoolean("bLineMode");
             m_sOCRResultLineMode = bun.getString("LineModeText");
             imgWidth = bun.getInt("imgWidth");
             imgHeight = bun.getInt("imgHeight");
        }    	
    }
	
	private void DisplayOcrResult()
	{		
		if (!m_bLineMode && OCR.m_iMeanConfidence < OCR.mConfig.m_iMinOveralConfidence)
			m_LocalMessageHandler.sendEmptyMessageDelayed(R.id.resultsactivity_displayWarning, 1000);
		
		try {
			if (!m_bLineMode)
				result_text.setText(OCR.m_ssOCRResult);
			else
				result_text.setText(m_sOCRResultLineMode);

			Toast.makeText(getBaseContext(), getString(R.string.resultsactivity_ocrbadresults_msg1) + " " + OCR.m_iMeanConfidence , Toast.LENGTH_LONG).show();
		
		} catch (Exception e) {
			Log.v(TAG, e.toString());
		}
	}
	
	@Override
    public boolean onKeyDown(int keyCode, KeyEvent event) 
	{		
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        	        	        
        if ( keyCode == KeyEvent.KEYCODE_BACK )	{ 	// if "BACK-KEY" pressed
            if (event.getRepeatCount() == 0)
            {            	
        		System.gc();
        		finish();            
            }
        }
        
        return super.onKeyDown(keyCode, event);
    }

	/** MENU */	
    @Override
    public boolean onCreateOptionsMenu(Menu menu) 
    {
      super.onCreateOptionsMenu(menu);
            
      m_sPreferencesMenu = menu;
      
      menu.add(PREFERENCES_GROUP_ID, SETTINGS_ID, 0, R.string.menu_settings)
          .setIcon(android.R.drawable.ic_menu_preferences);
      menu.add(PREFERENCES_GROUP_ID, IN_IMAGE_ID, 0, R.string.menu_in_image)
      		.setIcon(android.R.drawable.ic_menu_report_image);
      menu.add(PREFERENCES_GROUP_ID, ABOUT_ID, 0, R.string.menu_about)
          .setIcon(android.R.drawable.ic_menu_info_details);
      
      if (OCReader.CheckSDCardState() == false)
    	  menu.setGroupVisible(PREFERENCES_GROUP_ID, false);
      
      return true;
    } 
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) 
    {
      switch (item.getItemId()) {
        case SETTINGS_ID:
      	  OCR.ReadAvailableLanguages();
          m_bMenuSettings = true;
          Intent intent = new Intent(Intent.ACTION_VIEW);
          intent.setClassName(this, PreferencesActivity.class.getName());
          startActivity(intent);
          break;

        case IN_IMAGE_ID:
			m_LocalMessageHandler.sendEmptyMessage(R.id.resultsactivity_showinputimage);
        	break;
        case ABOUT_ID:
          break;
      }
      return super.onOptionsItemSelected(item);
    }
    
	private Handler m_LocalMessageHandler = new Handler() 
	{
		@Override
		public void handleMessage(Message msg) 
		{
			switch(msg.what)
			{
				case R.id.resultsactivity_displayWarning:
					AlertDialog.Builder builder = new AlertDialog.Builder(ResultsActivity.this);
					builder.setIcon(android.R.drawable.ic_dialog_alert);
				    builder.setTitle(R.string.resultsactivity_ocrbadresults_title);
				    builder.setMessage(getString(R.string.resultsactivity_ocrbadresults_msg1) + " " + OCR.m_iMeanConfidence +" " + getString(R.string.resultsactivity_ocrbadresults_msg2));
				    builder.setPositiveButton("Ok", null);
				    builder.show();		
				break;
				
				case R.id.resultsactivity_showinputimage:

					pdShowImage = ProgressDialog.show(ResultsActivity.this, getString(R.string.resultsactivity_working), 
							getString(R.string.resultsactivity_wait),true, true);
					pdShowImage.setOnCancelListener( new OnCancelListener() {
						public void onCancel(DialogInterface dialog) 
						{
							android.os.Process.killProcess(android.os.Process.myPid());
						}    		    		
					});

					Thread theOCRthread = new Thread(ResultsActivity.this);
					theOCRthread.start();
					
		        	break;
		        
				case R.id.resultsactivity_openimage:
					pdShowImage.dismiss();
					if(path!=null) 
					{
			        	Intent intent1 = new Intent();
			        	intent1.setAction(android.content.Intent.ACTION_VIEW);
			        	intent1.setDataAndType(Uri.fromFile(new File(path)), "image/png");
			        	startActivity(intent1);
					}
					else
			    		Toast.makeText(getBaseContext(), R.string.input_image_exception, 
			    				Toast.LENGTH_SHORT).show();
					break;
				case R.id.resultsactivity_showerror:
					pdShowImage.dismiss();
		    		Toast.makeText(ResultsActivity.this, R.string.input_image_exception, Toast.LENGTH_SHORT).show();
					break;
					
				default:
					break;
			}
			
			super.handleMessage(msg);
		}
		
	};
	
	public void run() 
	{
    	Bitmap bmp = null;
    	try{
    		if(OCReader.imageFromGallery)
    			bmp = OCR.get().GetInternImage(imgWidth, imgHeight);
    		else if(!m_bLineMode)
   				bmp = OCR.get().GetInternImage(1024, 768);
    		else
    			bmp = OCR.get().GetInternImage(512, 60);
    		path = OCReader.RESULTS_PATH + "test.png"; 
        	File file = new File(path); 
    		FileOutputStream fos = null;
    		try 
    		{
    			fos = new FileOutputStream(file);
    			bmp.compress(CompressFormat.PNG, 100, fos ); 
    			fos.close();
    		}
    		catch (Exception e) {
    			e.printStackTrace();
    		} 
    		m_LocalMessageHandler.sendEmptyMessage(R.id.resultsactivity_openimage);
    	} 
    	catch(Exception e) {
    		m_LocalMessageHandler.sendEmptyMessage(R.id.resultsactivity_showerror);
    		Log.e(TAG,"error");
    	}
	}
      
}
